<template>
  <a-modal
    :visible="visible"
    :afterClose="hanldeAfterClose"
    :width="1120"
    @cancel="handleCancel"
    @ok="handleOk"
    :confirmLoading="isSubmiting"
    :okText="$isEmpty(data) ? '添加' : '修改'"
    :title="$isEmpty(data) ? '新建计划' : '修改计划'"
  >
    <a-spin :spinning="spinning">
      <a-form :form="form" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
        <a-row :gutter="16" type="flex">
          <a-col :span="8">
            <a-form-item label="计划名称">
              <a-input
                v-decorator="['Name', { rules: [{ required: true, message: '请输入计划名称' }] }]"
                placeholder="请输入计划名称"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划年度">
              <year-picker
                v-decorator="['Years', { rules: [{ required: true, message: '请选择计划年度' }] }]"
                placeholder="请选择计划年度"
              >
              </year-picker>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划所属部门/单位">
              <a-cascader
                :show-search="{ filterDept }"
                v-decorator="['DeptID', { rules: [{ required: true, message: '请选择计划所属部门/单位' }] }]"
                placeholder="请选择计划所属部门/单位"
                :options="deptOptions"
                change-on-select
                :field-names="{ label: 'name', value: 'ID', children: 'children' }"
              >
                <span slot="displayRender" slot-scope="{ labels }">{{ labels.pop() }}</span>
              </a-cascader>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="开始时间">
              <a-date-picker
                v-decorator="['CreateDate', { rules: [{ required: true, message: '请选择开始时间' }] }]"
                placeholder="请选择开始时间"
                valueFormat="YYYY-MM-DD"
              >
              </a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="预计完成时间">
              <a-date-picker
                v-decorator="['PredictDate', { rules: [{ required: true, message: '请选择预计完成时间' }] }]"
                placeholder="请选择预计完成时间"
                valueFormat="YYYY-MM-DD"
              >
              </a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划总套数(套)">
              <a-input-number
                v-decorator="['GoalPiece', { rules: [{ required: true, message: '请输入计划总套数' }] }]"
                placeholder="请输入计划总套数"
                :formatter="(value) => `${value}套`"
              ></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划总资金(万元)">
              <a-input-number
                v-decorator="['PredictFund', { rules: [{ required: true, message: '请输入计划总资金' }] }]"
                placeholder="请输入计划总资金"
                :formatter="(value) => `${value}万元`"
              ></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划总面积(㎡)">
              <a-input-number
                v-decorator="['GoalArea', { rules: [{ required: true, message: '请输入计划总面积' }] }]"
                placeholder="请输入计划总面积"
                :formatter="(value) => `${value}㎡`"
              ></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="项目状态">
              <a-select
                v-decorator="['Mode', { rules: [{ required: true, message: '请选择项目状态' }] }]"
                placeholder="请选择项目状态"
              >
                <a-select-option :value="0">正常</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-form-item label="备注" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
              <a-textarea
                v-decorator="['Content', { initialValue: '' }]"
                placeholder="备注"
                :auto-size="{ minRows: 3, maxRows: 5 }"
              ></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <file-list
        v-if="visible"
        ref="fileList"
        category="SCTP"
        tableNames="ebll_No001YPlan"
        :fileList="detailData.SCWJJH"
        :option="{
          typeRequired: false,
        }"
      ></file-list>
    </a-spin>
  </a-modal>
</template>

<script>
import { yearPicker, fileList } from '@/components'
import { getDeptDropList } from '@/api/communityReviewManagement'
import { getProjectPlanDetail, postProjectPlan } from '@/api/followUpManagement'
import pick from 'lodash.pick'
import { treeFindPath } from '@/utils/util'
export default {
  components: {
    yearPicker,
    fileList
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    visible (n) {
      if (n) {
        this.fetchData()
      }
    }
  },
  data () {
    return {
      form: this.$form.createForm(this, { name: 'plan' }),
      isSubmiting: false,
      spinning: false,
      detailData: {},
      deptOptions: []
    }
  },
  methods: {
    fetchData () {
      this.spinning = true
      const getDept = getDeptDropList({
        userid: this.$store.getters.userid
      })
      const requestArr = [getDept]
      if (!this.$isEmpty(this.data)) {
        const getDetail = getProjectPlanDetail({
          ID: this.data.ID
        })
        requestArr.push(getDetail)
      }
      // 删除children为空的数据
      const deleteEmptyChildren = (data) => {
        data.forEach((e) => {
          if (this.$isEmpty(e.children)) {
            delete e.children
          } else {
            deleteEmptyChildren(e.children)
          }
        })
        return data
      }
      Promise.all(requestArr)
        .then((res) => {
          this.deptOptions = deleteEmptyChildren(res[0])
          if (!this.$isEmpty(this.data)) {
            this.detailData = res[1].data
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(res[1].data, [
                  'Name',
                  'Years',
                  'CreateDate',
                  'PredictDate',
                  'GoalPiece',
                  'PredictFund',
                  'GoalArea',
                  'Mode',
                  'Content'
                ])
              )
              this.form.setFieldsValue({
                DeptID: treeFindPath(this.deptOptions, data => data.ID === res[1].data.DeptID).map(e => e.ID)
              })
            })
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    close () {
      this.form.resetFields()
      this.detailData = {}
      this.deptOptions = []
      this.$emit('update:visible', false)
      this.$emit('update:data', {})
    },
    handleCancel () {
      this.close()
      this.hanldeAfterClose()
    },
    handleOk () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$refs.fileList.validateFields((fileErr, fileData) => {
            if (!fileErr) {
              Object.assign(values, {
                ID: this.data.ID || 0,
                LID: this.detailData.LID || 0,
                Creater: this.$store.getters.nickname,
                SCWJJH: fileData,
                DeptID: values.DeptID.pop()
              })
              this.isSubmiting = true
              const isAdd = this.$isEmpty(this.data)
              postProjectPlan({
                State: isAdd ? 'add' : 'update',
                palns: values
              })
                .then((res) => {
                  this.$message.success(isAdd ? '添加成功！' : '修改成功！')
                  this.$emit('success', isAdd)
                  this.close()
                })
                .finally(() => {
                  this.isSubmiting = false
                })
            }
          })
        }
      })
    },
    hanldeAfterClose () {},
    filterDept (inputValue, path) {
      return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-form-item-label {
  white-space: normal;
  padding-right: 12px;
}
/deep/ .ant-calendar-picker,
.ant-input-number {
  width: 100%;
}
</style>
